package com.motong.gongdan.controller.system;

import com.motong.gongdan.config.auth.PassToken;
import com.motong.gongdan.service.DeviceInfoService;
import io.swagger.annotations.Api;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Objects;

@Api(tags = "mqtt接口")
@RestController
@RequestMapping("/sys/mqtt")
public class MqttController {

    @Resource
    private DeviceInfoService deviceInfoService;

    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    @PostMapping("/online")
    @PassToken
    public void online(@RequestBody Map<String, Object> param) {
        System.out.println("上线通知");
        param.forEach((k, v) -> System.out.printf("获取到的key: %s, 获取到的value: %s%n", k, v.toString()));
        if (Objects.nonNull(param.get("clientId"))) {
            deviceInfoService.changeStatus(param.get("clientId").toString(), 1);
        }
    }

    @PostMapping("/offline")
    @PassToken
    public void offline(@RequestBody Map<String, Object> param) {
        System.out.println("下线通知");
        param.forEach((k, v) -> System.out.printf("获取到的key: %s, 获取到的value: %s%n", k, v.toString()));
        if (Objects.nonNull(param.get("clientId"))) {
            deviceInfoService.changeStatus(param.get("clientId").toString(), 4);
            redisTemplate.opsForHash().delete("deviceStatusCache", param.get("clientId").toString());
        }
    }


}
